package Hot100.Medium.LinkedList;

public class LC02_addTwoNumbersInList {
    public static void main(String[] args) {

    }

    public ListNode addTwoNumbers(ListNode n1, ListNode n2){
        ListNode dummyNode = new ListNode(0);
        ListNode cur = dummyNode;
        //初始化进位数
        int carry = 0;
        //遍历到n1 n2 以及进位数都为0时循环才结束
        while(n1 != null || n2 != null || carry != 0){
            int val1 = (n1 != null) ? n1.val : 0;
            int val2 = (n2 != null) ? n2.val : 0;
            //计算当前位的和以及进位
            int sum = val1 + val2 + carry;
            carry = sum / 10;
            //创建新节点并连接到链表
            cur.next = new ListNode(sum % 10);
            cur = cur.next;

            if(n1 != null) n1 = n1.next;
            if(n2 != null) n2 = n2.next;
        }
        return dummyNode.next;
    }
}
